/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/commons/json/serializer/ArraySerializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: ArraySerializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.serializer;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author elancom
 */
public class ArraySerializer implements ObjectSerializer {

	private final ObjectSerializer compObjectSerializer;

	public ArraySerializer(ObjectSerializer compObjectSerializer) {
		super();
		this.compObjectSerializer = compObjectSerializer;
	}

	@Override
	public final void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
		final SerializeWriter out = serializer.getWriter();

		if (object == null) {
			if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) {
				out.write("[]");
			} else {
				out.writeNull();
			}
			return;
		}

		final Object[] array = (Object[]) object;
		final int size = array.length;

		final int end = size - 1;

		if (end == -1) {
			out.append("[]");
			return;
		}

		final SerialContext context = serializer.getContext();
		serializer.setContext(context, object, fieldName);

		try {
			out.append('[');
			for (int i = 0; i < end; ++i) {
				final Object item = array[i];

				if (item == null) {
					out.append("null,");
				} else {
					compObjectSerializer.write(serializer, item, null, null);
					out.append(',');
				}
			}

			final Object item = array[end];

			if (item == null) {
				out.append("null]");
			} else {
				compObjectSerializer.write(serializer, item, null, null);
				out.append(']');
			}
		} finally {
			serializer.setContext(context);
		}
	}
}
